import { responseError } from '@/server/apiResponse';
import { AppError } from '@/server/appError';
import { ErrorCode } from '@/server/common/error-code.enum';
import { HTTPSTATUS } from '@/server/common/http-status-code';
import { articleRoutes } from '@/server/routes/articleRoutes';
import { authRoutes } from '@/server/routes/authRoutes';
import { jiebaRoutes } from '@/server/routes/jiebaRoutes';
import { secuRoutes } from '@/server/routes/secuRoutes';
import { Hono } from 'hono';

const app = new Hono().basePath('/api');
export const routes = app
    .route('/auth', authRoutes)
    .route('/secu', secuRoutes)
    .route('/jieba', jiebaRoutes)
    .route('/article', articleRoutes);

export const errorHandler = (err, c) => {
    let resp;
    console.log('============================== Caught Error ==============================');
    console.error(err);
    console.log('==========================================================================');

    if (err instanceof SyntaxError) {
        resp = responseError({ message: ErrorCode.BAD_REQUEST });
        return c.json(resp, HTTPSTATUS.BAD_REQUEST);
    }

    if (err instanceof AppError) {
        resp = responseError({ message: err.errorCode });
        return c.json(resp, HTTPSTATUS.OK);
    }

    resp = responseError({ message: '服务暂不可用' });
    return c.json(resp, HTTPSTATUS.OK);
};

app.onError(errorHandler);
